//
//  HMEmoticonKeyboard.swift
//  Weibo02
//
//  Created by teacher on 16/4/26.
//  Copyright © 2016年 teacher. All rights reserved.
//  表情键盘

import UIKit

class HMEmoticonKeyboard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        // 设置要执行的闭包
        toolBar.emoticonButtonClickClosure = { (type)->() in
            print(type)
            //
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            self.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            // 设置pageControl的数据显示
            self.showPageControl(indexPath)

        }
        
        // 添加子控件
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        // 添加约束
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(self)
            make.height.equalTo(37)
        }
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(toolBar.snp_top)
            make.centerX.equalTo(toolBar)
        }
        // 需要在界面完成展示出来之后再去移动（collectionView大小已经确定，已经走过一遍数据源方法/ 主线程空闲的时候）
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            
            self.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            // 选中底部的按钮
            self.toolBar.selectSection = indexPath.section
            // 设置pageControl显示的内容
            self.showPageControl(indexPath)
        }

    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: SCREENW, height: self.frame.height - toolBar.frame.height)
    }
    
    // MARK: - 懒加载控件
    
    private lazy var emoticonCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        // layout.itemSize = CGSize(width: SCREENW, height: 216-37)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        // 设置布局方向
        layout.scrollDirection = .Horizontal
        
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.clearColor()
        // 注册cell
        collectionView.registerClass(HMEmoticonPageCell.self, forCellWithReuseIdentifier: "cell")
        // 设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
        // 去掉弹簧效果
        collectionView.bounces = false
        // 分页
        collectionView.pagingEnabled = true
        // 隐藏滚动条
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    private lazy var toolBar: HMEmoticonToolBar = HMEmoticonToolBar(frame: CGRectZero)
    
    //添加分页控件
    private lazy var pageControl:UIPageControl = {
        
        let pageControl = UIPageControl()
        //设置默认隐藏在最近使用表情里面不显示
        pageControl.hidden = true
        //设置不同状态下的图片
    
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        
        //关闭用户交互
        pageControl.userInteractionEnabled = false
       
        return pageControl
    }()
    
    
}

extension HMEmoticonKeyboard: UICollectionViewDataSource,UICollectionViewDelegate {
    
    //返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return HMEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons.count
    }
    //返回的每一组里面有多少个表情
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[section].count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存中取
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as!HMEmoticonPageCell
        
        cell.indexPath = indexPath
        
        //设置每一个cell的数组
        cell.emoticons = HMEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[indexPath.section][indexPath.item]
        
      
        return cell
    }
    
    //监听collectionView的滚动，判断当前滚动到第几组，再去选中对应组的按钮
    func scrollViewDidScroll(scrollView:UIScrollView){
        
        //取到中心点用来判断
        var center = scrollView.center
        // 当前collectionView的中间 + 滚动的距离
        center.x = center.x + scrollView.contentOffset.x
        
        
        //取到contentView 当前显示的cell
        let cells = emoticonCollectionView.visibleCells()
        
        //设置一个索引常量记录 常量通常有一次赋值的机会
        let indexPath:NSIndexPath
        //如果有两个cell表示正在滑动 当前显示面有两个cell
        if cells.count == 2 {
            
            //判断那一个cell显示的多 取到第一个和最后一个cell
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            //取到显示得多的那个cell的indexPath
            //判断第一个cell的范围是否包含当前计算出来的center  如果存在就赋值
            if CGRectContainsPoint(firstCell.frame, center){
                //求出firstCell的section
                indexPath = emoticonCollectionView.indexPathForCell(firstCell)!
                
            }else{
                // 求出lastCell的section
                indexPath = emoticonCollectionView.indexPathForCell(lastCell)!
            }
        }else{
            
            //如果不等于二就表示没有移动
            indexPath = emoticonCollectionView.indexPathForCell(cells.first!)!
        }
        
        //设置toolBar对应选中的按钮
        toolBar.selectSection = indexPath.section
        //展示相对应的pageControl
        showPageControl(indexPath)
        
    }
    
    //设置pageControl显示的内容
    private func showPageControl(indexPath:NSIndexPath){
        
        //设置总页数  应该是每一组的分页数
        pageControl.numberOfPages = HMEmoticonKeyBoardViewModel.sharedViewModel.allEmoticons[indexPath.section].count
        
        //设置当前页
        pageControl.currentPage = indexPath.item
        //设置显示  如果不是最近表情
        pageControl.hidden = indexPath.section == 0
    }
    
}



